package com.quyunshuo.edwinusetime.common.utils

import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
object LightSensorManager : SensorEventListener {
    // 使用独立的协程作用域，与传感器生命周期绑定
    private val coroutineScope = CoroutineScope(Dispatchers.Default + SupervisorJob())

    private var sensorManager: SensorManager? = null
    private var lightSensor: Sensor? = null
    private var isListening = false

    private val _lightValue = MutableStateFlow(0f)
    val lightValue = _lightValue.asStateFlow()

    // 添加状态Flow，让调用者知道当前传感器状态
    private val _sensorState = MutableStateFlow<SensorState>(SensorState.Idle)
    val sensorState = _sensorState.asStateFlow()

    sealed class SensorState {
        object Idle : SensorState()
        object Initializing : SensorState()
        object Active : SensorState()
        data class Error(val message: String) : SensorState()
    }

    fun initialize(context: Context, samplingRate: Int = SensorManager.SENSOR_DELAY_NORMAL) {
        if (isListening) return

        _sensorState.value = SensorState.Initializing

        try {
            sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
            lightSensor = sensorManager?.getDefaultSensor(Sensor.TYPE_LIGHT)

            if (lightSensor == null) {
                _sensorState.value = SensorState.Error("光线传感器不可用")
                return
            }

            val isRegistered = sensorManager?.registerListener(this, lightSensor, samplingRate) ?: false
            if (isRegistered) {
                isListening = true
                _sensorState.value = SensorState.Active
            } else {
                _sensorState.value = SensorState.Error("注册传感器失败")
            }
        } catch (e: Exception) {
            _sensorState.value = SensorState.Error("初始化传感器失败: ${e.message}")
            e.printStackTrace()
        }
    }

    fun stopListening() {
        if (!isListening) return

        sensorManager?.unregisterListener(this)
        isListening = false
        _sensorState.value = SensorState.Idle
    }

    fun isSensorAvailable(): Boolean {
        return lightSensor != null
    }

    // 动态调整采样率
    fun adjustSamplingRate(samplingRate: Int) {
        if (isListening && lightSensor != null) {
            sensorManager?.unregisterListener(this)
            sensorManager?.registerListener(this, lightSensor, samplingRate)
        }
    }

    override fun onSensorChanged(event: SensorEvent) {
        if (event.sensor.type == Sensor.TYPE_LIGHT) {
            val lux = event.values[0]
            // StateFlow的emit是线程安全的，不需要在协程中调用 协程内优先用emit()，非协程环境优先用value
            _lightValue.value = lux
        }
    }

    override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {}

    // 允许自定义光照状态判断逻辑
    fun updateBrightnessStatus(lux: Float): String {
        return when {
            lux > 2000 -> "有害强光！建议避免直视光源"
            lux > 500 -> "光线过强，注意护眼"
            lux > 50 -> "舒适光照"
            else -> "光线较暗"
        }
    }

    // 提供自定义判断逻辑的接口
    fun interface BrightnessStatusProvider {
        fun getStatus(lux: Float): String
    }
}
